package action;

import gate.ActionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Util;
import dm.ManagerDM;

public class ActionManager implements ActionHandler{

	public void handleAction(HttpServletRequest request, HttpServletResponse response) {

		try{
			String action = request.getParameter("action");
			
			String url = request.getParameter("url");
			ManagerDM dm = new ManagerDM();
			
			try{
				if (action.equals("addFirm")) {
					
					String name = request.getParameter("firmName");
					String desc = request.getParameter("firmDesc");
					
					dm.addFirm(name, desc);
					
				}else if (action.equals("updateFirm")) {
					
					int id = Util.toInt(request.getParameter("firmId"));
					String name = request.getParameter("firmName");
					String desc = request.getParameter("firmDesc");
					
					dm.updateFirm(id, name, desc);
					
				}else if (action.equals("deleteFirm")) {
					
					int id = Util.toInt(request.getParameter("firmId"));
					
					dm.deleteFirm(id);
					
				}else if (action.equals("insertProduct")) {
					
					int count = Integer.parseInt(request.getParameter("count"));
					int proId = Integer.parseInt(request.getParameter("proId"));
					Double price = Double.parseDouble(request.getParameter("price"));
					
					dm.insertProduct(proId,price,count);
					
				}else if (action.equals("addProduct")) {
					
					String name = request.getParameter("name");
					String brand = request.getParameter("brand");
					String description = request.getParameter("description");
					int firmId = Util.toInt(request.getParameter("firmId"));
					String categoryId = request.getParameter("categoryId");
					Double kdv = Double.parseDouble(request.getParameter("kdv"));
					
					dm.addProduct(name, brand,description, firmId, categoryId, kdv);
				
				}else if (action.equals("updateProduct")) {
					
					int id = Util.toInt(request.getParameter("firmId"));
					String name = request.getParameter("name");
					String brand = request.getParameter("brand");
					String description = request.getParameter("description");
					int groupId = Util.toInt(request.getParameter("groupId"));
					String categoryId = request.getParameter("categoryId");
					Double kdv = Double.parseDouble(request.getParameter("kdv"));
					
					dm.updateProduct(id, name, brand,description, groupId, categoryId, kdv);
					
				}else if (action.equals("deleteProduct")) {
					
					int id = Util.toInt(request.getParameter("firmId"));
					
					dm.deleteProduct(id);
				}
			} catch (Exception e) {
				
				request.setAttribute("error", e.getMessage());
				// TODO: handle exception
			}
			
			request.getRequestDispatcher(url).forward(request, response);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
